package com.gzzyy.unionchain.ui.business.transfer

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.gzzyy.unionchain.App
import com.gzzyy.unionchain.LiveEvent
import com.gzzyy.unionchain.R
import com.gzzyy.unionchain.data.ObjectBox
import com.gzzyy.unionchain.databinding.ActivityTransferBinding
import com.gzzyy.unionchain.ui.base.BaseActivity
import com.gzzyy.unionchain.util.KeyUtil
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class TransferActivity : BaseActivity() {

    private var balance = 0f
    private val commitTimeOutRun = Runnable {
        ToastUtils.showShort("转账提交超时")
    }
    private lateinit var binding: ActivityTransferBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTransferBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbar.setNavigationOnClickListener {
            finish()
        }

        GlobalScope.launch {
            val utxo = findUtxo(App.user?.walletAddress)
            Log.i("test", "balance = $balance")
            withContext(Dispatchers.Main) {
                if (utxo <= 0) {
                    binding.balanceTv.text = "0.00"
                } else {
                    binding.balanceTv.text = "$utxo"
                    balance = utxo
                }
            }
        }
        binding.transferAllTv.setOnClickListener {
            binding.transferValueEt.setText(binding.balanceTv.text.toString())
        }
        binding.receiveAddressTv.setOnClickListener {
            if (binding.receiveAddressEt.visibility == View.GONE) {
                binding.receiveAddressEt.visibility = View.VISIBLE
                binding.receiveAddressTv.setBackgroundResource(R.drawable.shape_transfer_text_bg_top_radius)
            } else {
                if (binding.receiveAddressEt.text.toString().isEmpty()) {
                    binding.receiveAddressEt.visibility = View.GONE
                    binding.receiveAddressTv.setBackgroundResource(R.drawable.shape_transfer_text_bg)
                }
            }
        }
        binding.contactBookImageView.setOnClickListener {

        }
        binding.receiveAddressEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                binding.transferConfirmBtn.isEnabled = s != null && s.isNotEmpty()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        binding.senderAddressTv.text = App.user?.walletAddress
        binding.transferConfirmBtn.setOnClickListener {
            if (binding.transferValueEt.text.toString().isNotEmpty()) {
                val transValue = binding.transferValueEt.text.toString().toFloat()
                if (transValue <= balance) {
                    val transferAddress = binding.receiveAddressEt.text.toString()
                    if (transferAddress.isNotEmpty()) {
                        it.isEnabled = false
                        binding.transferCommitProgressBar.show()
                        // 进行转账
                        GlobalScope.launch {
                            val preHash = findPreHash()
                            val nonce = UUID.randomUUID().toString()
                            val createTime = (System.currentTimeMillis() / 1000).toString()
                            val hash = KeyUtil.getTransferHash(preHash, nonce, createTime)
                            val jsonObj = KeyUtil.combineTransferBean(
                                App.user?.walletAddress,
                                transferAddress,
                                transValue,
                                findUtxo(App.user?.walletAddress) - transValue,
                                findUtxo(transferAddress) + transValue,
                                nonce,
                                preHash,
                                transferBeanBox.all.size,
                                hash,
                                KeyUtil.getTransferHashSign(hash),
                                createTime
                            )
                            LiveEventBus.get(LiveEvent.CommitTransfer).post(jsonObj)
                            LiveEventBus.get(LiveEvent.MessageToOther).post(jsonObj)
                            handler.postDelayed({ commitTimeOutRun }, 3000)
                        }
                    } else {
                        ToastUtils.showShort("请输入接收地址")
                    }
                } else {
                    ToastUtils.showShort("转账金额超过余额，请重新输入")
                }
            } else {
                ToastUtils.showShort("请输入转账金额")
            }
        }
        LiveEventBus.get(LiveEvent.TransferResponse)
            .observe(this@TransferActivity, androidx.lifecycle.Observer {
                ToastUtils.showShort("转账提交成功")
            })
    }

    private val transferBeanBox = ObjectBox.getRecordBox()
    private fun findUtxo(walletAddress: String?): Float {
        return KeyUtil.findBalance(walletAddress)
    }

    private fun findPreHash(): String {
        val transferBean = transferBeanBox.all.last()
        if (transferBean != null) {
            return transferBean.hash
        }
        return ""
    }
}